package com.zhengb.algorithmdemo.basic.linklist;

/**
 * @author zhengbo
 * @date 2020/2/15
 */
public class ReverseListNodeKGroup {


    private static class ListNode {

        int val;

        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    private static ListNode getEndNode(ListNode headNode) {

        ListNode curNode = headNode;

        while (curNode.next != null) {
            curNode = curNode.next;
        }

        return curNode;

    }

    public static ListNode reverseKGroup(ListNode head, int k) {

        ListNode preNode = null;
        ListNode curNode = head;
        ListNode nextNode = null;

        while (k-- > 0) {
            nextNode = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = nextNode;
        }

        ListNode endNode = getEndNode(preNode);

        endNode.next = curNode;
        //curNode.next = nextNode;
        //preNode的尾节点指向curNode
        return preNode;
    }


    public static void printList(ListNode headNode) {

        if (headNode.next == null) {
            System.out.println(headNode.val);
        }

        ListNode curNode = headNode;

        while (curNode != null) {
            System.out.println(curNode.val);
            curNode = curNode.next;
        }
    }

    public static void main(String[] args) {

        ListNode firstNode = new ListNode(1);
        ListNode secondNode = new ListNode(2);
        ListNode thirdNode = new ListNode(3);
        ListNode fourthNode = new ListNode(4);
        ListNode fifthhNode = new ListNode(5);

        firstNode.next = secondNode;
        secondNode.next = thirdNode;
        thirdNode.next = fourthNode;
        fourthNode.next = fifthhNode;

        ListNode listNode = reverseKGroup(firstNode, 3);

        printList(listNode);

    }
}
